package com.zhongge.jdbc;


import com.mysql.cj.jdbc.Driver;

import java.sql.*;

/**
 * @ClassName JDBCTest01
 * @Description TODO
 * @Author zhongge
 * @Version 1.0
 */
public class JDBCTest01 {
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try {
            //第一步：注册驱动
            //方式一：手动注册
            Driver driver = new com.mysql.cj.jdbc.Driver();
            DriverManager.deregisterDriver(driver);

            //方式二：使用反射自动注册
            Class.forName("com.mysql.cj.jdbc.Driver");

            //第二步：获取连接
            String url = "jdbc:mysql://localhost:3306/test";
            String username = "root";
            String password = "123456";
            conn = DriverManager.getConnection(url, username, password);

            //第三步：获取操作数据库对象
            stmt = conn.createStatement();

            // 1. 编写SQL语句（准备"指令"）:添加
            /*String sql = "insert into t_user(name,password,realname,gender,tel) " +
                    "values('tangsanzang','123456','唐三藏','男','13800138000')";*/

            // 2. 执行SQL（发送"指令"）
            // executeUpdate返回受影响的行数（成功插入1条记录，返回1）
            /*int count = stmt.executeUpdate(sql);*/

            /*String sql = "update t_user set password='654321' where name='tangsanzang'";
            int count = stmt.executeUpdate(sql);
            System.out.println("更新了" + count + "条记录");*/

          /*  String sql = "delete from t_user where id=1";
            int count = stmt.executeUpdate(sql);
            System.out.println("删除了" + count + "条记录");*/

            //注意：增删改使用的是：executeUpdate(aql)
            //查询使用的是    sexecuteQuery(sql)

            String sql = "select * from t_user";

            PreparedStatement pstmt = conn.prepareStatement(sql);
            ResultSet re =pstmt.executeQuery();
            while (re.next()) {
                int id = re.getInt("id");
                String name = re.getString("name");
                String pwd =  re.getString("password");
                String realName = re.getString("realname");
                String gender = re.getString("gender");
                String tel = re.getString("tel");

                System.out.println(id + "\t\t" + name + "\t\t" + pwd + "\t\t" + realName + "\t\t" + gender + "\t\t" + tel);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e){
            e.printStackTrace();
        }

    }
}
